package com.qijian.plug.capacity.approval;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qijian.common.core.domain.entity.FlowableModelRefApproval;
import com.qijian.common.core.domain.entity.SysRole;
import com.qijian.common.core.domain.entity.SysUser;
import com.qijian.common.enums.ApprovalDescriptionEnum;
import com.qijian.flowable.constant.FlowableConstant;
import com.qijian.flowable.domain.Flow;
import com.qijian.flowable.domain.FlowableRecord;
import com.qijian.flowable.domain.FlowableRecordPower;
import com.qijian.flowable.domain.vo.ProcessInstanceVo;
import com.qijian.flowable.service.IFlowableRecordPowerService;
import com.qijian.flowable.service.IFlowableRecordService;
import com.qijian.flowable.service.IProcessInstanceService;
import com.qijian.flowable.domain.vo.FlowVo;
import com.qijian.flowable.service.IFlowService;
import com.qijian.system.mapper.SysRoleMapper;
import com.qijian.system.mapper.SysUserMapper;
import lombok.RequiredArgsConstructor;
import org.flowable.engine.HistoryService;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.repository.ProcessDefinitionQuery;
import org.flowable.variable.api.history.HistoricVariableInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@RequiredArgsConstructor
public class ApprovalModelRefProcess extends ApprovalPlugWrapper<FlowableModelRefApproval.Approval> {

    private final IFlowableRecordService flowableRecordService;

    private final HistoryService historyService;

    private final IFlowableRecordPowerService flowableRecordPowerService;

    private final IProcessInstanceService processInstanceService;

    private final RepositoryService repositoryService;

    private final IFlowService flowService;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysUserMapper userMapper;

    @Override
    public void doSomething(List<Object> args) {
        try {
            FlowVo o = (FlowVo) args.get(0);
            String userId = args.get(1).toString();
            FlowableRecord flowableRecord = flowableRecordService.getOne(new LambdaQueryWrapper<FlowableRecord>().eq(FlowableRecord::getSourceId, o.getId()).eq(FlowableRecord::getBusinessKey, o.getFlowType()));
            Map<String, Object> varMap = new HashMap<>();
            if (flowableRecord != null) {
                flowableRecord.setStatus(ApprovalDescriptionEnum.T.getValue());
                flowableRecord.setIsDel(true);
                flowableRecordService.updateStatusByReStart(flowableRecord);
                Flow flow = new Flow();
                flow.setId(o.getId());
                flow.setApprovalStatus(ApprovalDescriptionEnum.B);
                flowService.updateById(flow);
                FlowableRecordPower recordPower = new FlowableRecordPower();
                recordPower.setProcessIntaneId(flowableRecord.getProcessInstanceId());
                recordPower.setType(FlowableConstant.TH);
                recordPower.setUserId(Long.parseLong(userId));
                flowableRecordPowerService.save(recordPower);
                List<HistoricVariableInstance> list = historyService.createHistoricVariableInstanceQuery().processInstanceId(flowableRecord.getProcessInstanceId()).list();
                list.stream().forEach(e -> {
                    varMap.put(e.getVariableName(), e.getValue());
                });
                varMap.put("anti", "Y");
                SysRole role1 = new SysRole();
                role1.setRoleKey("flow_djshr");
                List<SysRole> sysRoles1 = roleMapper.selectRoleList(role1);
                if (CollectionUtil.isNotEmpty(sysRoles1)) {
                    SysUser user = new SysUser();
                    user.setRoleId(sysRoles1.get(0).getRoleId());
                    List<SysUser> sysUsers = userMapper.selectAllocatedList(user);
                    if (CollectionUtil.isNotEmpty(sysUsers)) {
                        varMap.put("djshr", sysUsers.get(0).getUserId() );
                    }
                }
                // 查询流程
                ProcessDefinitionQuery processDefinitionQuery = repositoryService.createProcessDefinitionQuery();
                processDefinitionQuery.processDefinitionKey(o.getFlowType()).latestVersion();
                ProcessDefinition definition = processDefinitionQuery.singleResult();
                if (ObjectUtil.isNotNull(definition)) {
                    // 流程数据
                    ProcessInstanceVo instanceVo = new ProcessInstanceVo();
                    instanceVo.setProcessDefinitionId(definition.getId());

                    instanceVo.setValues(varMap);
                    instanceVo.setSourceId(o.getId());
                    // 发起流程
                    Map<String, Object> result = processInstanceService.start(instanceVo);

                }
            }

            System.out.println(args);
        }catch (SecurityException e) {

        }


    }
}
